﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Core.Tasks
{
    /// <summary>
    /// 任务监视器，用于计数器，用于任务失败通知
    /// </summary>
    static class TaskMonitor
    {
        private static Dictionary<int, long> monitors = new Dictionary<int, long>();

        /// <summary>
        /// 递增
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public static long Increment(int type)
        {
            lock (monitors)
            {
                long value;
                if (monitors.TryGetValue(type, out value))
                {
                    value++;
                }
                else
                {
                    value = 1L;
                }
                monitors[type] = value;
                return value;
            }
        }

        /// <summary>
        /// 读取
        /// </summary>
        /// <param name="type"></param>
        /// <param name="IsReset"></param>
        /// <returns></returns>
        public static long Read(int type, bool IsReset)
        {
            lock (monitors)
            {
                long value;
                if (!monitors.TryGetValue(type, out value))
                {
                    value = 0L;
                }
                else
                {
                    if (IsReset)
                    {
                        monitors[type] = 0L;
                    }
                }
                return value;
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public static long Init(int type)
        {
            lock (monitors)
            {
                long value = 1L;
                monitors[type] = value;
                return value;
            }
        }

        /// <summary>
        /// 递减
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public static long Decrement(int type)
        {
            lock (monitors)
            {
                long value;
                if (monitors.TryGetValue(type, out value))
                {
                    value--;
                    if (value < 0)
                    {
                        value = 0L;
                    }
                }
                else
                {
                    value = 0L;
                }
                monitors[type] = value;
                return value;
            }
        }

    }
}
